import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Demo12Semaphore {

    /**
     * 信号量，维护一个许可证的计数，许可证为0是，剩余现成需要等待。
     * @param args
     */
    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "\t 抢到车位");
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + "\t 停车3秒后离开车位");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    semaphore.release();
                }
            }, "Thread-Car-" + i).start();
        }
    }

}
